﻿package idv.cjcat.emitter {
	use namespace engine;
	
	import flash.display.*;
	import flash.errors.*;
	import flash.geom.*;
	
	import idv.cjcat.emitter.geom.*;
	
	/**
	 * DisplayObject-based particle source.
	 */
	public class DisplayObjectSource extends ParticleSource {
		
		private var _displayObject:DisplayObject;
		private var _spawnCoords:Vector.<int>;
		private var _x:Number, _y:Number;
		
		public function DisplayObjectSource(displayObject:DisplayObject) {
			_spawnCoords = new Vector.<int>();
			this.displayObject = displayObject;
		}
		
		override public function spawnPos():MotionData2D {
			var index:int = Math.floor(Math.random() * _spawnCoords.length * 0.5) * 2;
			
			if (_spawnCoords.length == 0) return new MotionData2D( -Number.MAX_VALUE, -Number.MAX_VALUE);
			return new MotionData2D(x + _x + _spawnCoords[index], y + _y + _spawnCoords[index + 1]);
		}
		
		/**
		 * The base display object.
		 * <p>
		 * Every time this value is set.
		 * The source updates its particle spawning region.
		 * The region is the part of the display object where the transparency(alpha) is non-zero.
		 * Based on the display object, a source of any shape can be created.
		 * </p>
		 */
		public function get displayObject():DisplayObject { return _displayObject; }
		public function set displayObject(value:DisplayObject):void {
			_displayObject = value;
			
			var rect:Rectangle = _displayObject.getBounds(_displayObject);
			rect.width = Math.ceil(rect.width);
			rect.height = Math.ceil(rect.height);
			_x = rect.x;
			_y = rect.y;
			
			var bmpd:BitmapData = new BitmapData(rect.width, rect.height, true, 0x00000000);
			bmpd.draw(_displayObject, new Matrix(1, 0, 0, 1, -rect.x, -rect.y));
			
			var colors:Vector.<uint> = bmpd.getVector(new Rectangle(0, 0, bmpd.width, bmpd.height));
			_spawnCoords.length = 0;
			for (var i:uint = 0; i < colors.length; i++) {
				var color:uint = colors[i];
				if ((color >>> 24) > 0) {
					_spawnCoords.push(i % bmpd.width);
					_spawnCoords.push(Math.floor(i / bmpd.width));
				}
			}
		}
		
		
		//XML
		//------------------------------------------------------------------------------------------------
		
		override public function toXML():XML {
			throw new IllegalOperationError("This class does not support XML.");
			return null;
		}
		
		//------------------------------------------------------------------------------------------------
		//end of XML
	}
}